package edu.contoller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.annotations.LoginRequired;
import edu.entity.Do.*;
import edu.entity.Vo.BillVo;
import edu.entity.Vo.ProductVo;
import edu.mapper.*;
import edu.utils.JwtUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * 用于处理 订单请求   比如第一个方法 "doBill" 就是用于下单的，方法的含义可以从方法名称解读出
 * 比如第二个方法 "getBillVoByUserId" => "根据 userId 获取 订单" Vo 为 view Object 表示视图层实体
 * BusinessController  CartController  ProductController  ProductImageController  StoreController  UserController 同理
 */
@RestController
@RequestMapping(value = "/user")
@CrossOrigin(origins = "*",maxAge = 3600)
public class BillController {
    @Resource
    BillMapper billMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    ProductMapper productMapper;

    @Resource
    CartMapper cartMapper;

    @Resource
    ProductImageMapper productImageMapper;

    @Resource
    StoreMapper storeMapper;

    @LoginRequired
    @RequestMapping(value = "/doBill",method = RequestMethod.POST)
    public Integer doBill(Integer productId, String address, String phone, Double price,HttpServletRequest request,Integer cartId) {
        Integer id = Integer.parseInt(JwtUtil.getClaims(request.getHeader("token")).get("id").asString());
        User user = userMapper.selectById(id);
        if (user.getBalance() > price) {
            Product product = productMapper.selectById(productId);
            if (product.getRemain() <= 0) {
                return -2;
            }else {
                product.setRemain(product.getRemain() - 1);
                product.setSaleNumber(product.getSaleNumber() + 1);
                productMapper.updateById(product);
                user.setBalance(user.getBalance() - price);
                userMapper.updateById(user);
                Bill bill = new Bill();
                bill.setBusinessId(product.getBusinessId());
                bill.setCreateTime(DateTime.now());
                bill.setAddress(address);
                bill.setPhone(phone);
                bill.setProductId(productId);
                bill.setUserId(id);

                cartMapper.deleteById(cartId);
                return billMapper.insert(bill);
            }
        }else {
            return -1;
        }
    }


    @LoginRequired
    @RequestMapping(value = "/getBillVoByUserId",method = RequestMethod.GET)
    public List<BillVo> getBillVoByUserId(HttpServletRequest request) {
        Integer id = Integer.parseInt(JwtUtil.getClaims(request.getHeader("token")).get("id").asString());
        List<Bill> bills = billMapper.selectList(
                new QueryWrapper<Bill>()
                        .eq("user_id", id)
        );
        List<BillVo> billVos = new ArrayList<>();

        for (Bill bill : bills) {
            BillVo billVo = new BillVo();
            ProductVo productVo = new ProductVo();
            Product product = productMapper.selectById(bill.getProductId());

            Store store = storeMapper.selectOne(
                    new QueryWrapper<Store>()
                            .eq("business_id", product.getBusinessId())
            );

            billVo.setStoreName(store.getStoreName());

            BeanUtil.copyProperties(product,productVo);
            ProductImage product_id = productImageMapper.selectOne(
                    new QueryWrapper<ProductImage>()
                            .eq("product_id", product.getId())
            );

            productVo.setPath(product_id.getPath());
            productVo.setCreateTime(DateUtil.format(product.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            billVo.setProductVo(productVo);

            BeanUtil.copyProperties(bill,billVo);
            billVo.setCreateTime(DateUtil.format(bill.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            if (bill.getState() == 0) {
                billVo.setState("正在准备发货");
            }else if (bill.getState() == 1) {
                billVo.setState("运输中");
            }else {
                billVo.setState("已完成");
            }

            billVos.add(billVo);
        }
        return billVos;
    }



    @LoginRequired
    @RequestMapping(value = "/getBillVoByBusinessId",method = RequestMethod.GET)
    public List<BillVo> getBillVoByBusinessId(HttpServletRequest request) {
        Integer id = Integer.parseInt(JwtUtil.getClaims(request.getHeader("token")).get("id").asString());
        List<Bill> bills = billMapper.selectList(
                new QueryWrapper<Bill>()
                        .eq("business_id", id)
        );
        List<BillVo> billVos = new ArrayList<>();
        for (Bill bill : bills) {
            BillVo billVo = new BillVo();
            ProductVo productVo = new ProductVo();
            Product product = productMapper.selectById(bill.getProductId());

            Store store = storeMapper.selectOne(
                    new QueryWrapper<Store>()
                            .eq("business_id", product.getBusinessId())
            );
            billVo.setStoreName(store.getStoreName());

            BeanUtil.copyProperties(product,productVo);
            ProductImage product_id = productImageMapper.selectOne(
                    new QueryWrapper<ProductImage>()
                            .eq("product_id", product.getId())
            );
            productVo.setPath(product_id.getPath());
            productVo.setCreateTime(DateUtil.format(product.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            billVo.setProductVo(productVo);

            BeanUtil.copyProperties(bill,billVo);
            billVo.setCreateTime(DateUtil.format(bill.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            if (bill.getState() == 0) {
                billVo.setState("尚未发货");
            }else if (bill.getState() == 1) {
                billVo.setState("等待顾客收货");
            }else {
                billVo.setState("已完成");
            }

            billVos.add(billVo);
        }
        return billVos;
    }

    @LoginRequired
    @RequestMapping(value = "/billLunch",method = RequestMethod.GET)
    public Integer billLunch(Integer billId) {
        Bill bill = billMapper.selectById(billId);
        bill.setState(1);
        return billMapper.updateById(bill);
    }
}
